<template>
<div :data-active="active" @dragenter.prevent="setActive" @dragover.prevent="setActive" @dragleave.prevent="setInactive" @drop.prevent="onDrop"><slot :dropZoneActive="active"></slot>
</div>
<!--template><div :data-active="active" @dragenter.prevent="setActive" @dragover.prevent="setActive" @dragleave.prevent="setInactive" @drop.prevent="onDrop"><slot :dropZoneActive="active"><label for="file-input"-->
</template>

<script setup>
//https://www.smashingmagazine.com/2022/03/drag-drop-file-uploader-vuejs-3/

import { ref, onMounted, onUnmounted } from 'vue'
const emit = defineEmits(['files-dropped'])

let active = ref(false)
let inActiveTimeout = null // add a variable to hold the timeout key

function setActive() {
        active.value = true
        clearTimeout(inActiveTimeout) // clear the timeout
}
function setInactive() {
        // wrap it in a `setTimeout`
        inActiveTimeout = setTimeout(() => {
                active.value = false
        }, 50)
}

function onDrop(e) {
    emit('files-dropped', [...e.dataTransfer.files])
}

function preventDefaults(e) {
    e.preventDefault()
}

const events = ['dragenter', 'dragover', 'dragleave', 'drop']

onMounted(() => {
    events.forEach((eventName) => {
            document.body.addEventListener(eventName, preventDefaults)
    })
})

onUnmounted(() => {
    events.forEach((eventName) => {
            document.body.removeEventListener(eventName, preventDefaults)
    })
})
</script>